#ifndef YHAIDA_TCPCLIENT_H
#define YHAIDA_TCPCLIENT_H
#include "../base/Utils.h"
#include "../mutex/MutexLock.h"
#include "../logging/Logging.h"
#include "Callbacks.h"
#include "TcpConnection.h"
#include "SocketsOps.h"
#include "EventLoop.h"
#include <functional>

namespace yhaida
{
    class Connector;
    typedef std::shared_ptr<Connector> ConnectorPtr;

    /*
    TcpClient就像TcpConnection一样包装一个连接,这两个是映射噶
    */
    class TcpClient : Utils::nocapyable
    {
    public:
        TcpClient(EventLoop *loop, const InetAddress &serverAddr);
        ~TcpClient();

        void connect();
        TcpConnectionPtr connection() const;
        void disconnect();
        void stop();

        bool retry() const { return _retry; }
        void enableRetry() { _retry = true; }

        //用户的接口
        void setConnectionCallback(const ConnectionCallback &cb)
        {
            _connectionCallback = cb;
        }
        void setMessageCallback(const MessageCallback &cb)
        {
            _messageCallback = cb;
        }
        void setWriteCompleteCallback(const WriteCompleteCallback &cb)
        {
            _writeCompleteCallback = cb;
        }

    private:
        void newConnection(int sockfd);
        void removeConnection(const TcpConnectionPtr &conn);

    private:
        EventLoop *_mainEventLoop;
        ConnectorPtr _connector;

        ConnectionCallback _connectionCallback;
        MessageCallback _messageCallback;
        WriteCompleteCallback _writeCompleteCallback;

        bool _retry;
        bool _start;

        int _nextConnID;
        mutable MutexLock _mutex;
        TcpConnectionPtr _connection;
    };
}
#endif